﻿using Digitalmes.Services.Tenant;
using Microsoft.AspNetCore.Http;
using System.Linq;
using System.Threading.Tasks;

namespace Digitalmes.Middlewares
{
    //// 启用租户中间件
    //app.UseMiddleware<TenantMiddleware>();
    public class TenantMiddleware
    {
        private readonly RequestDelegate _next;

        public TenantMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        //public async Task Invoke(HttpContext context)
        //{
        //    await _next(context);
        //}


        public async Task Invoke(HttpContext context, ITenantProvider tenantProvider)
        {
            // 从请求中解析租户ID (多种方式)
            var tenantId = ResolveTenant(context);

            if (!string.IsNullOrEmpty(tenantId))
            {
                tenantProvider.SetTenant(tenantId);
            }

            await _next(context);
        }

        private string ResolveTenant(HttpContext context)
        {
            // 1. 从子域名解析 (tenant.mydomain.com)
            var host = context.Request.Host.Host;
            if (host.Contains('.'))
            {
                return host.Split('.')[0];
            }

            // 2. 从路由参数解析 (/api/{tenant}/products)
            if (context.Request.RouteValues.TryGetValue("tenant", out var routeTenant))
            {
                return routeTenant?.ToString();
            }

            // 3. 从Header解析
            return context.Request.Headers["X-Tenant-Id"].FirstOrDefault();
        }
    }
}
